
package edu.weber.bookstore.util;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

/**
 * 
 * 
 */
public class DatabaseConnection
{
	private static final String DATABASE_HOST = "mc.martyj.net";
	private static final String DATABASE_PORT = "3306";
	private static final String DATABASE_NAME = "advanced_java";
	private static final String DATABASE_USERNAME = "bookstore";
	private static final String DATABASE_PASSWORD = "kDesG83hAn5";
	private static DatabaseConnection _databaseConnection = null;
	private DriverManagerDataSource _dataSource;
	
	private DatabaseConnection()
	{
		_dataSource = new DriverManagerDataSource();
		_dataSource.setDriverClassName("com.mysql.jdbc.Driver");
		_dataSource.setUrl("jdbc:mysql://".concat(DATABASE_HOST).concat(":").concat(DATABASE_PORT).concat("/").concat(DATABASE_NAME));
		_dataSource.setUsername(DATABASE_USERNAME);
		_dataSource.setPassword(DATABASE_PASSWORD);
	}
	
	/**
	 * Used for connecting to and from the database.
	 * @return Returns a java.sql.Connection object for the application's database connection.
	 * @throws SQLException 
	 */
	public static Connection getConnection() throws SQLException
	{
		if(_databaseConnection == null)
		{
			_databaseConnection = new DatabaseConnection();
		}
		
		return _databaseConnection._dataSource.getConnection();
	}
	
	/**
	 * 
	 * @param pm A prepared insert statement to which you wish to get the ID from.
	 * Must include Statement.RETURN_GENERATED_KEYS as a param in the prepared statement creation.
	 * @return int of last inserted database id. 0 if no last inserted id.
	 * @throws SQLException 
	 */
	public static int lastInsertedId(Statement pm) throws SQLException
	{
		ResultSet rs =	pm.getGeneratedKeys();
		if(rs.next())
		{
			return rs.getInt(1);
		}
		
		return 0;
	}
}

